<template>
  <div class="space-y-6">
        <div class="card">
          <div class="font-semibold mb-3">家庭成员</div>
          <div class="space-y-3">
            <div v-for="member in familyMembers" :key="member.id" class="flex items-center justify-between p-3 rounded bg-bg">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-primary flex items-center justify-center text-white text-sm font-semibold">
                  {{ member.nickname.charAt(0) }}
                </div>
                <div>
                  <div class="font-medium">{{ member.nickname }}</div>
                  <div class="text-sm text-gray-500">{{ member.role === 'PARENT' ? '家长' : '监护人' }}</div>
                  <div class="text-xs text-gray-400">加入时间：{{ formatDate(member.joinedAt) }}</div>
                </div>
              </div>
              <div class="flex gap-2">
                <button 
                  v-if="member.id !== userStore.currentUser?.id" 
                  @click="removeMember(member.id)"
                  class="px-3 py-1 text-sm text-red-500 hover:bg-red-50 rounded"
                >
                  移除
                </button>
              </div>
            </div>
          </div>
      <div class="flex gap-2 mt-3">
        <button class="btn-accent flex-1" @click="showInviteModal = true">邀请家人</button>
        <button class="btn-accent flex-1" @click="showJoinFamilyModal = true">加入家庭</button>
      </div>
    </div>

    <div class="card">
      <div class="font-semibold mb-3">个人信息</div>
      <div class="space-y-3">
        <div class="flex items-center justify-between p-3 rounded bg-bg">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-full bg-primary flex items-center justify-center text-white text-sm font-semibold">
              {{ userStore.currentUser?.nickname?.charAt(0) || 'U' }}
            </div>
            <div>
              <div class="font-medium">{{ userStore.currentUser?.nickname || '用户' }}</div>
              <div class="text-sm text-gray-500">{{ userStore.currentUser?.role === 'PARENT' ? '家长' : '监护人' }}</div>
            </div>
          </div>
          <button 
            @click="openUserProfileModal"
            class="px-3 py-1 text-sm text-primary hover:bg-primary/10 rounded"
          >
            编辑
          </button>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="font-semibold mb-3">宝宝档案管理</div>
      
      <!-- 现有宝宝列表 -->
      <div v-if="userStore.familyBabies.length > 0" class="mb-4">
        <div class="text-sm text-gray-600 mb-2">现有宝宝</div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div v-for="baby in userStore.familyBabies" :key="baby.id" class="flex items-center gap-3 p-3 border rounded">
            <img v-if="baby.avatarUrl" class="w-12 h-12 rounded-full object-cover" :src="baby.avatarUrl" alt="baby" />
            <div v-else class="w-12 h-12 rounded-full bg-primary flex items-center justify-center text-white font-semibold">
              {{ baby.nickname?.charAt(0) || '👶' }}
            </div>
            <div class="flex-1">
              <div class="font-medium">{{ baby.nickname }}</div>
              <div class="text-sm text-gray-500">{{ baby.gender === 'M' ? '男孩' : '女孩' }} · {{ formatBirthday(baby.birthday) }}</div>
            </div>
            <div class="flex gap-1">
              <button class="btn-primary text-xs px-2 py-1" @click="editBaby(baby)">编辑</button>
              <button class="btn-accent text-xs px-2 py-1" @click="deleteBaby(baby.id)" v-if="userStore.familyBabies.length > 1">删除</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 新增/编辑宝宝表单 -->
      <div class="border-t pt-4">
        <div class="text-sm text-gray-600 mb-2">{{ editingBaby ? '编辑宝宝' : '添加新宝宝' }}</div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
          <input class="input" placeholder="昵称" v-model="baby.nickname" />
          <input class="input" type="date" placeholder="生日" v-model="baby.birthday" />
          <select class="input" v-model="baby.gender">
            <option :value="'M'">男孩</option>
            <option :value="'F'">女孩</option>
          </select>
          <input class="input" placeholder="头像URL（可选）" v-model="baby.avatarUrl" />
        </div>
        <div class="flex gap-2 mt-3">
          <button class="btn-primary" @click="saveBaby" :disabled="loading">
            {{ loading ? '保存中...' : (editingBaby ? '更新' : '添加') }}
          </button>
          <button v-if="editingBaby" class="btn-accent" @click="cancelEdit">取消</button>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="font-semibold mb-3">通知设置</div>
      <div class="space-y-3">
        <label class="flex items-center gap-2">
          <input type="checkbox" v-model="setting.notifyFeeding" />
          <span>喂奶提醒</span>
        </label>
        <label class="flex items-center gap-2">
          <input type="checkbox" v-model="setting.notifySleep" />
          <span>睡眠提醒</span>
        </label>
        <label class="flex items-center gap-2">
          <input type="checkbox" v-model="setting.notifyDiaper" />
          <span>换尿布提醒</span>
        </label>
      </div>
      <button class="btn-primary mt-3" @click="saveSetting" :disabled="loading">
        {{ loading ? '保存中...' : '保存设置' }}
      </button>
    </div>

    <!-- 邀请家人模态框 -->
    <div v-if="showInviteModal" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
      <div class="card w-full max-w-md">
        <div class="text-lg font-semibold mb-4">邀请家人</div>
        <form @submit.prevent="sendInvite">
          <div class="space-y-3">
            <label class="block">
              <span class="text-sm">邮箱地址</span>
              <input v-model="inviteEmail" class="input mt-1" type="email" placeholder="请输入家人邮箱" required />
            </label>
            <label class="block">
              <span class="text-sm">角色</span>
              <select v-model="inviteRole" class="input mt-1">
                <option value="PARENT">家长</option>
                <option value="GUARDIAN">监护人</option>
              </select>
            </label>
            <label class="block">
              <span class="text-sm">邀请消息</span>
              <textarea v-model="inviteMessage" class="input mt-1" rows="3" placeholder="可输入邀请消息...（可选）" />
            </label>
          </div>
          <div class="flex justify-end gap-2 mt-4">
            <button type="button" class="px-4 py-2 rounded bg-bg" @click="showInviteModal = false">取消</button>
            <button type="submit" class="btn-primary" :disabled="loading">发送邀请</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 加入家庭模态框 -->
    <div v-if="showJoinFamilyModal" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
      <div class="card w-full max-w-md">
        <div class="text-lg font-semibold mb-4">加入家庭</div>
        <form @submit.prevent="joinFamily">
          <div class="space-y-3">
            <label class="block">
              <span class="text-sm">邀请码</span>
              <input v-model="joinInviteCode" class="input mt-1" placeholder="请输入邀请码" required />
            </label>
            <div class="text-xs text-gray-500">
              邀请码由家庭成员通过"邀请家人"功能生成
            </div>
          </div>
          <div class="flex justify-end gap-2 mt-4">
            <button type="button" class="px-4 py-2 rounded bg-bg" @click="showJoinFamilyModal = false">取消</button>
            <button type="submit" class="btn-primary" :disabled="loading">加入家庭</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 邀请码分享模态框 -->
    <div v-if="showInviteCodeModal" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
      <div class="card w-full max-w-md">
        <div class="text-lg font-semibold mb-4">邀请码分享</div>
        
        <div class="space-y-4">
          <!-- 邀请码显示 -->
          <div class="bg-bg p-4 rounded-lg border">
            <div class="text-sm text-gray-600 mb-2">邀请码</div>
            <div class="flex items-center gap-2">
              <input 
                :value="inviteCodeData.code" 
                readonly 
                class="flex-1 px-3 py-2 bg-white border rounded font-mono text-lg"
                id="inviteCodeInput"
              />
              <button 
                @click="copyInviteCode" 
                class="px-4 py-2 bg-primary text-white rounded hover:opacity-80"
              >
                {{ copySuccess ? '已复制' : '复制' }}
              </button>
            </div>
          </div>

          <!-- 分享信息 -->
          <div class="text-sm text-gray-600">
            <div class="mb-2">
              <strong>{{ inviteCodeData.familyName }}</strong> 邀请您加入家庭
            </div>
            <div class="text-xs">
              有效期至：{{ new Date(inviteCodeData.expiresAt).toLocaleString() }}
            </div>
          </div>


          <!-- 使用说明 -->
          <div class="bg-blue-50 p-3 rounded text-sm text-blue-800">
            <div class="font-medium mb-1">使用说明：</div>
            <div>1. 将邀请码发送给家人</div>
            <div>2. 家人注册账号后，在"家庭与设置"页面输入邀请码</div>
            <div>3. 即可成功加入家庭</div>
          </div>
        </div>

        <div class="flex justify-end gap-2 mt-6">
          <button 
            class="px-4 py-2 rounded bg-bg" 
            @click="showInviteCodeModal = false"
          >
            关闭
          </button>
        </div>
      </div>
    </div>

    <!-- 个人信息编辑模态框 -->
    <div v-if="showUserProfileModal" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
      <div class="card w-full max-w-md">
        <div class="text-lg font-semibold mb-4">编辑个人信息</div>
        <form @submit.prevent="updateUserProfile">
          <div class="space-y-3">
            <label class="block">
              <span class="text-sm">昵称</span>
              <input v-model="userProfile.nickname" class="input mt-1" placeholder="请输入昵称" required />
            </label>
          </div>
          <div class="flex justify-end gap-2 mt-4">
            <button type="button" class="px-4 py-2 rounded bg-bg" @click="showUserProfileModal = false">取消</button>
            <button type="submit" class="btn-primary" :disabled="loading">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useUserStore } from '../stores/user';
import { type FamilySetting, type BabyProfile, API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function getFamily(familyId: number) {
  const token = localStorage.getItem('auth_token');
  console.log('Settings getFamily - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${familyId}`, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    }
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function getFamilyBabies(familyId: number) {
  const token = localStorage.getItem('auth_token');
  console.log('Settings getFamilyBabies - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${familyId}/babies`, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    }
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function updateFamilySettings(familyId: number, setting: FamilySetting) {
  const token = localStorage.getItem('auth_token');
  console.log('Settings updateFamilySettings - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${familyId}/settings`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(setting)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function upsertBaby(familyId: number, baby: BabyProfile) {
  const token = localStorage.getItem('auth_token');
  console.log('Settings upsertBaby - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${familyId}/baby`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(baby)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const userStore = useUserStore();
const setting = reactive<FamilySetting>({ notifyFeeding: true, notifySleep: false, notifyDiaper: true });
const baby = reactive<BabyProfile>({ nickname: '', birthday: '', gender: 'F', avatarUrl: '' });
const loading = ref(false);
const editingBaby = ref<BabyProfile | null>(null);

// 邀请家人相关变量
const showInviteModal = ref(false);
const inviteEmail = ref('');
const inviteRole = ref('PARENT');
const inviteMessage = ref('');

// 加入家庭相关变量
const showJoinFamilyModal = ref(false);
const joinInviteCode = ref('');

// 邀请码分享相关变量
const showInviteCodeModal = ref(false);
const inviteCodeData = ref({
  code: '',
  expiresAt: '',
  familyName: '',
  inviterNickname: ''
});
const copySuccess = ref(false);

// 家庭成员相关变量
const familyMembers = ref([]);

// 个人信息相关变量
const showUserProfileModal = ref(false);
const userProfile = ref({
  nickname: ''
});

async function load() {
  if (!userStore.currentUser?.familyId) return;

  try {
    loading.value = true;
    const familyId = userStore.currentUser.familyId;

    // 加载家庭信息
    const fam = await getFamily(familyId);
    if (fam?.settings) {
      setting.notifyFeeding = fam.settings.notifyFeeding ?? true;
      setting.notifySleep = fam.settings.notifySleep ?? false;
      setting.notifyDiaper = fam.settings.notifyDiaper ?? true;
    }

    // 加载宝宝信息
    const babies = await getFamilyBabies(familyId);
    userStore.setFamilyBabies(babies || []);

    // 清空表单，准备添加新宝宝
    resetBabyForm();
  } catch (error) {
    console.error('加载家庭信息失败:', error);
  } finally {
    loading.value = false;
  }
}

async function saveSetting() {
  if (!userStore.currentUser?.familyId) return;

  try {
    await updateFamilySettings(userStore.currentUser.familyId, setting);
    alert('通知设置已保存');
  } catch (error) {
    console.error('保存设置失败:', error);
    alert('保存失败，请重试');
  }
}

// 重置宝宝表单
function resetBabyForm() {
  baby.nickname = '';
  baby.birthday = '';
  baby.gender = 'F';
  baby.avatarUrl = '';
  baby.id = undefined;
  editingBaby.value = null;
}

// 编辑宝宝
function editBaby(babyToEdit: BabyProfile) {
  editingBaby.value = babyToEdit;
  baby.id = babyToEdit.id;
  baby.nickname = babyToEdit.nickname || '';
  baby.birthday = babyToEdit.birthday || '';
  baby.gender = babyToEdit.gender || 'F';
  baby.avatarUrl = babyToEdit.avatarUrl || '';
}

// 取消编辑
function cancelEdit() {
  resetBabyForm();
}

// 删除宝宝
async function deleteBaby(babyId: number) {
  if (!confirm('确定要删除这个宝宝吗？删除后无法恢复！')) return;

  try {
    loading.value = true;
    const token = localStorage.getItem('auth_token');
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${userStore.currentUser?.familyId}/baby/${babyId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token || ''}`
      }
    });

    if (!resp.ok) {
      const errorText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }

    alert('宝宝档案已删除');

    // 重新加载宝宝列表
    const babies = await getFamilyBabies(userStore.currentUser?.familyId!);
    userStore.setFamilyBabies(babies);

    // 如果删除的是当前选择的宝宝，切换到第一个宝宝
    if (userStore.currentBabyId === babyId) {
      if (babies.length > 0) {
        userStore.switchBaby(babies[0].id!);
      } else {
        userStore.currentBabyId = null;
      }
    }

    // 重置表单
    resetBabyForm();
  } catch (error) {
    console.error('删除宝宝失败:', error);
    alert('删除失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 格式化生日显示
function formatBirthday(birthday: string) {
  if (!birthday) return '未设置';
  const date = new Date(birthday);
  return date.toLocaleDateString('zh-CN');
}

async function saveBaby() {
  if (!userStore.currentUser?.familyId) return;
  if (!baby.nickname || !baby.birthday) {
    alert('请填写昵称和生日');
    return;
  }

  try {
    loading.value = true;
    const result = await upsertBaby(userStore.currentUser.familyId, baby);
    alert(editingBaby.value ? '宝宝档案已更新' : '宝宝档案已添加');

    // 重新加载宝宝列表
    const babies = await getFamilyBabies(userStore.currentUser.familyId);
    userStore.setFamilyBabies(babies);

    // 如果是新增宝宝且是第一个宝宝，自动设置为当前宝宝
    if (!editingBaby.value && babies.length === 1) {
      userStore.switchBaby(babies[0].id!);
    }

    // 重置表单
    resetBabyForm();
  } catch (error) {
    console.error('保存宝宝档案失败:', error);
    alert('保存失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 发送邀请
async function sendInvite() {
  if (!inviteEmail.value) {
    alert('请输入邮箱地址');
    return;
  }

  try {
    loading.value = true;
    const token = localStorage.getItem('auth_token');
    const familyId = userStore.currentUser?.familyId;
    
    if (!familyId) {
      alert('无法获取家庭ID，请重新登录');
      return;
    }
    
    console.log('发送邀请 - 家庭ID:', familyId, '用户信息:', userStore.currentUser);
    
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${familyId}/invite`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token || ''}`
      },
      body: JSON.stringify({
        email: inviteEmail.value,
        role: inviteRole.value,
        message: inviteMessage.value
      })
    });

    if (!resp.ok) {
      const errorText = await resp.text();
      if (resp.status === 409) {
        throw new Error('该邮箱的邀请已存在，请检查是否已经发送过邀请');
      }
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }

    const result = await resp.json();
    
    // 显示邀请码分享模态框
    showInviteCodeModal.value = true;
    inviteCodeData.value = {
      code: result.inviteCode,
      expiresAt: result.expiresAt,
      familyName: result.familyName || '我的家庭',
      inviterNickname: result.inviterNickname || '我'
    };
    
    // 重置表单
    inviteEmail.value = '';
    inviteRole.value = 'PARENT';
    inviteMessage.value = '';
    showInviteModal.value = false;
  } catch (error) {
    console.error('发送邀请失败:', error);
    alert('发送邀请失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 加入家庭
async function joinFamily() {
  if (!joinInviteCode.value) {
    alert('请输入邀请码');
    return;
  }

  try {
    loading.value = true;
    const token = localStorage.getItem('auth_token');
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/invite/${joinInviteCode.value}/accept`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token || ''}`
      },
      body: JSON.stringify({
        accept: true
      })
    });

    if (!resp.ok) {
      const errorText = await resp.text();
      if (resp.status === 410) {
        throw new Error('邀请码已过期或已处理，请重新获取邀请码');
      }
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }

    const result = await resp.json();
    alert('成功加入家庭！');
    showJoinFamilyModal.value = false;
    joinInviteCode.value = '';
    
    // 重新获取用户信息（包含新的家庭信息）
    await refreshUserInfo();
    
    // 重新加载页面数据
    await load();
  } catch (error) {
    console.error('加入家庭失败:', error);
    alert('加入家庭失败，请检查邀请码是否正确');
  } finally {
    loading.value = false;
  }
}

// 复制邀请码
async function copyInviteCode() {
  try {
    await navigator.clipboard.writeText(inviteCodeData.value.code);
    copySuccess.value = true;
    setTimeout(() => {
      copySuccess.value = false;
    }, 2000);
  } catch (error) {
    // 降级方案：使用传统方法
    const input = document.getElementById('inviteCodeInput') as HTMLInputElement;
    if (input) {
      input.select();
      document.execCommand('copy');
      copySuccess.value = true;
      setTimeout(() => {
        copySuccess.value = false;
      }, 2000);
    }
  }
}

// 刷新用户信息
async function refreshUserInfo() {
  try {
    const token = localStorage.getItem('auth_token');
    if (!token) return;
    
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/auth/me`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (resp.ok) {
      const userData = await resp.json();
      userStore.setUser(userData.user);
      console.log('用户信息已更新:', userData.user);
    } else {
      console.error('获取用户信息失败:', resp.status);
    }
  } catch (error) {
    console.error('刷新用户信息失败:', error);
  }
}

// 加载家庭成员
async function loadFamilyMembers() {
  if (!userStore.currentUser?.familyId) return;
  
  try {
    const token = localStorage.getItem('auth_token');
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${userStore.currentUser.familyId}/members`, {
      headers: {
        'Authorization': `Bearer ${token || ''}`
      }
    });
    
    if (resp.ok) {
      familyMembers.value = await resp.json();
    }
  } catch (error) {
    console.error('加载家庭成员失败:', error);
  }
}

// 移除家庭成员
async function removeMember(memberId: number) {
  if (!confirm('确定要移除这个家庭成员吗？')) return;
  
  try {
    loading.value = true;
    const token = localStorage.getItem('auth_token');
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${userStore.currentUser?.familyId}/members/${memberId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token || ''}`
      }
    });
    
    if (resp.ok) {
      alert('成员已移除');
      await loadFamilyMembers();
    } else {
      const errorText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }
  } catch (error) {
    console.error('移除成员失败:', error);
    alert('移除成员失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 更新用户个人信息
async function updateUserProfile() {
  if (!userProfile.value.nickname) {
    alert('请输入昵称');
    return;
  }
  
  try {
    loading.value = true;
    const token = localStorage.getItem('auth_token');
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/auth/profile`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token || ''}`
      },
      body: JSON.stringify({
        nickname: userProfile.value.nickname
      })
    });
    
    if (resp.ok) {
      const result = await resp.json();
      userStore.setUser(result.user);
      alert('个人信息已更新');
      showUserProfileModal.value = false;
    } else {
      const errorText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }
  } catch (error) {
    console.error('更新个人信息失败:', error);
    alert('更新失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 打开个人信息编辑模态框
function openUserProfileModal() {
  userProfile.value.nickname = userStore.currentUser?.nickname || '';
  showUserProfileModal.value = true;
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleDateString('zh-CN');
}

onMounted(async () => {
  await load();
  await loadFamilyMembers();
});
</script>

<style scoped></style>